package org.mao.coque.websocket;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * @ServerEndpoint 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端, 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint(value = "/websocket/connect", configurator = WebSocketConfigurator.class)
public class WebSocketChat {

	private final static Logger logger = Logger.getLogger(WebSocketChat.class);

	/**
	 * 连接建立成功调用的方法
	 * 
	 * @param session 可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
	 */
	@OnOpen
	public void onOpen(Session session, EndpointConfig config) {
		HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
		logger.info("onOpen: " + httpSession);

		String nickName = (String) httpSession.getAttribute("nickName");
		logger.info("onOpen: " + nickName);
		
		session.setMaxIdleTimeout(0);

		if (StringUtils.isBlank(nickName)) {
			//OnlineConstants.notifyError(session, "浏览器版本过旧或不支持");
		} else {
			session.getUserProperties().put("nickName", nickName);
			//OnlineConstants.online(nickName, session);
			//OnlineConstants.notifyOnline(nickName);
			logger.info("新聊天成员加入: " + nickName);
		}
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose() {
		logger.info("onClose");
		new Thread(new Runnable() {
			@Override
			public void run() {
				//String nickName = OnlineConstants.offline();
				//OnlineConstants.notifyOffline(nickName);
				//logger.info(nickName + " 离开了");
			}
		}).start();
	}

	/**
	 * 收到客户端消息后调用的方法
	 * 
	 * @param message 客户端发送过来的消息
	 * @param session 可选的参数
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		logger.info("onMessage");
		String nickName = (String) session.getUserProperties().get("nickName");
		//OnlineConstants.notifyChatMessage(nickName, message);
		logger.info(nickName + "说: " + message);
	}

	/**
	 * 发生错误时调用
	 * 
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		logger.error("onError: ", error);
	}
}
